package com.topvision.common.token;

import com.topvision.common.exception.BusinessException;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;

/**
 * @author shengwm
 * @version V0.0.1
 * @Title: RawAccessToken
 * @Package com.seed.security.auth.jwt
 * @Description: TODO
 * @date 2017/6/16
 */
@Slf4j
public class RawAccessToken {
    private String token;

    public RawAccessToken(String token) {
        this.token = token;
    }

    /**
     * 解析和验证JWT令牌
     *
     * @param signingKey
     * @return
     */
    public Jws<Claims> parseClaims(String signingKey) {
        try {
            return Jwts.parser().setSigningKey(signingKey).parseClaimsJws(this.token);
        } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) {
            log.error("无效的JWT令牌", ex);
            throw new BusinessException("invalid JWT token", "无效的JWT令牌");
        } catch (ExpiredJwtException expiredEx) {
            log.info("JWT令牌过期", expiredEx);
            throw new BusinessException("expire JWT Token", "JWT令牌过期");
        }
    }
}
